//
//  KARepaymentDetailHeader.swift
//  kano
//
//  Created by Frank on 2024/9/19.
//

import UIKit
import RxCocoa
import RxSwift

class KARepaymentDetailHeader: UIView {
    
    override init(frame: CGRect) {
        super.init(frame: frame)
        ka_setUI()
        ka_bindUI()
    }
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    lazy var var_cornerView: UIView = {
        let var_cornerView = UIView()
        var_cornerView.backgroundColor = .white
        var_cornerView.layer.cornerRadius = kscale(16)
        var_cornerView.layer.masksToBounds = true
        return var_cornerView
    }()
    
    lazy var var_bgView: UIView = {
        let var_bgView = UIView()
        var_bgView.backgroundColor = .colorF4F4FD
        var_bgView.layer.cornerRadius = kscale(16)
        var_bgView.layer.masksToBounds = true
        return var_bgView
    }()
    
    public var symbolLabel: UILabel = {
        let label = UILabel()
        label.numberOfLines = 1
        label.font = UIFont.systemFont(ofSize: kscale(24), weight: .bold)
        label.textColor = .black
        label.text = "₦"
        return label
    }()
    
    lazy var contentTF: UITextField = {
        let contentTF = UITextField()
        contentTF.font = UIFont.systemFont(ofSize: kscale(24), weight: .bold)
        contentTF.placeholder = "0"
        contentTF.textColor = .black
        contentTF.keyboardType = .numberPad
        return contentTF
    }()
    
    lazy var clearBtn: UIButton = {
        let button = UIButton()
        button.setImage(UIImage(named: "input_clear"), for: .normal)
        return button
    }()
    
    lazy var rightBtn: UIButton = {
        let button = UIButton()
        button.setTitle("", for: .normal)
        button.setTitleColor(.themeColor, for: .normal)
        button.titleLabel?.font = UIFont.systemFont(ofSize: kscale(10), weight: .medium)
        //button.addTarget(self, action: #selector(totalBalanceClick), for: .touchUpInside)
        return button
    }()
    
    lazy var var_lineView: UIView = {
        let var_lineView = UIView()
        var_lineView.backgroundColor = .colorE2E1E3
        return var_lineView
    }()
    
    lazy var var_tipLabel: UILabel = {
        let var_tipLabel = UILabel()
        var_tipLabel.font = UIFont.systemFont(ofSize: kscale(11), weight: .regular)
        var_tipLabel.textColor = .colorFF8A2A
        var_tipLabel.textAlignment = .left
        var_tipLabel.text = ""
        return var_tipLabel
    }()
    lazy var var_subTipLabel: UILabel = {
        let var_subTipLabel = UILabel()
        var_subTipLabel.font = UIFont.systemFont(ofSize: kscale(11), weight: .regular)
        var_subTipLabel.textColor = .colorFF8A2A
        var_subTipLabel.textAlignment = .left
        var_subTipLabel.isHidden = true
        var_subTipLabel.text = "Fully paid off, can waive the amount of  ₦\(model?.transactionUserType?.first?.remainingFunds ?? 0)"
        return var_subTipLabel
    }()
    
    private let disposeBag = DisposeBag()

    
    var model: KABillDetailModel? {
        didSet {
            updateUI()
        }
    }
    
    var handler: (()->())?
    
    @objc func totalBalanceClick() {
//        guard let subloans = model?.transactionUserType else { return }

        //大额、蝌蚪贷
        if model?.secondaryLoanTotal ?? 0 > 0 {
            let subloans = model!.transactionUserType!
            for subLoan in subloans {
                subLoan.select = false
            }
            subloans.first?.select = true
            contentTF.text = subloans.first!.remainingFunds.separatorString()
        } 
        //小额
        else {
            contentTF.text = model?.registrationConfirmation.separatorString()
        }
        
        if handler != nil {
            handler!()
        }
    }
    
    func ka_bindUI() {
        contentTF.rx.text
            .orEmpty
            .subscribe(onNext: { [self] text in
                
                //去除字符串中的千分位分隔符
                var cleanedString = text.replacingOccurrences(of: ",", with: "")
                if let number = Double(cleanedString) {
                    //输入金额，最大不超过待还总金额；
                    if number > model?.registrationConfirmation ?? 0.0 {
                        var dropLastNum = number / 10
                        contentTF.text = "\(dropLastNum.separatorString())"
                        return
                    }
                    
                    guard let subloans = model?.transactionUserType else { return }
                    //遍历前清空标记
                    for subLoan in subloans {
                        subLoan.select = false
                    }
                    //遍历标记刚好符合输入金额的分期账单
                    var selectTotal = 0.00
                    for subLoan in subloans {
                        subLoan.select = true
                        selectTotal = subLoan.remainingFunds + selectTotal
                        if number <= selectTotal {
                            break
                        }
                    }
                }
                
                if handler != nil {
                    handler!()
                }
            })
            .disposed(by: disposeBag)
    }
    
    private func updateUI() {
        guard let model = model else { return }
        
        var subLoans: [KABillDetailSubLoans] = []
        var allSelected: [KABillDetailSubLoans] = []
        if model.transactionUserType?.count ?? 0 > 0 {
            subLoans = model.transactionUserType!
            allSelected = model.transactionUserType!.filter { $0.select }
        }

        //如果是蝌蚪贷，只展示第一期金额
        if model.tadpoleLoanIndicator {
            var amount = allSelected.first?.remainingFunds ?? 0.0
            contentTF.text = "\(amount.separatorString())"
            var_subTipLabel.isHidden = false
            var_subTipLabel.text = "Fully paid off, can waive the amount of  ₦\(model.transactionUserType?.last?.remainingFunds ?? 0)"
        }
        //大额
        else if model.secondaryLoanTotal  > 0 {
            var amount = 0.00
            for subLoan in allSelected {
                amount = amount + subLoan.remainingFunds
            }
            contentTF.text = "\(amount.separatorString())"
            var_subTipLabel.isHidden = true
        } 
        //小额
        else {
            contentTF.text = "\(model.registrationConfirmation.separatorString())"
        }
        
        //下面提示语
        //蝌蚪贷
        if model.tadpoleLoanIndicator {
            var subLoanModel = subLoans.first
            var_tipLabel.isHidden = false
            var_tipLabel.text = "Repayment amount for the 1-\(subLoans.count) period: ₦\(subLoanModel!.remainingFunds.separatorString())"
        }
        //大额
        if model.secondaryLoanTotal > 0 {
            var_tipLabel.isHidden = false
            var_tipLabel.text = "Repayment amount for the 1-\(subLoans.count) period: ₦\(model.registrationConfirmation.separatorString())"
        }
        //小额
        else {
            var_tipLabel.isHidden = false
            var_tipLabel.text = "Repayment amount: ₦\(model.registrationConfirmation.separatorString())"
        }
    }
    
}

extension KARepaymentDetailHeader {
    
    func ka_setUI() {
        backgroundColor = .colorF4F4FD
        addSubview(var_cornerView)
        addSubview(var_bgView)

        var_bgView.addSubview(symbolLabel)
        var_bgView.addSubview(rightBtn)
        var_bgView.addSubview(contentTF)
        var_bgView.addSubview(clearBtn)
        var_bgView.addSubview(var_lineView)
        var_bgView.addSubview(var_tipLabel)
        var_bgView.addSubview(var_subTipLabel)
        
        
        var_cornerView.snp.makeConstraints { make in
            make.top.equalTo(kscale(12))
            make.bottom.equalTo(kscale(-12))
            make.left.right.equalTo(self)
        }
        var_bgView.snp.makeConstraints { make in
            make.top.equalTo(kscale(28))
            make.bottom.equalTo(kscale(-28))
            make.left.equalTo(kscale(12))
            make.right.equalTo(kscale(-12))
        }
        symbolLabel.snp.makeConstraints { make in
            make.top.equalTo(kscale(20))
            make.left.equalTo(kscale(12))
            make.width.equalTo(kscale(16))
        }
        rightBtn.snp.makeConstraints { make in
            make.centerY.equalTo(symbolLabel)
            make.right.equalTo(kscale(-12))
            make.width.equalTo(kscale(75))
        }
        contentTF.snp.makeConstraints { make in
            make.centerY.equalTo(symbolLabel)
            make.left.equalTo(symbolLabel.snp.right).offset(kscale(10))
            make.right.equalTo(rightBtn.snp.left).offset(kscale(-10))
        }
        clearBtn.snp.makeConstraints { make in
            make.centerY.equalTo(symbolLabel)
            make.size.equalTo(CGSizeMake(20, 20))
            make.right.equalTo(rightBtn.snp.left).offset(kscale(-10))
        }
        clearBtn.snp.makeConstraints { make in
            make.centerY.equalTo(symbolLabel)
            make.size.equalTo(CGSizeMake(20, 20))
            make.right.equalTo(rightBtn.snp.left).offset(kscale(-10))
        }
        var_lineView.snp.makeConstraints { make in
            make.left.equalTo(kscale(12))
            make.right.equalTo(kscale(-12))
            make.height.equalTo(1)
            make.top.equalTo(symbolLabel.snp.bottom).offset(8)
        }
        var_tipLabel.snp.makeConstraints { make in
            make.left.equalTo(kscale(12))
            make.right.equalTo(kscale(-12))
            make.top.equalTo(var_lineView.snp.bottom).offset(12)
        }
        
        var_subTipLabel.snp.makeConstraints { make in
            make.left.equalTo(kscale(12))
            make.right.equalTo(kscale(-12))
            make.top.equalTo(var_tipLabel.snp.bottom).offset(4)
        }
    }
}
